package modelo;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import entities.MesaEntity;
import hbt.AbstractHibernateManager;


public class MesaDao extends AbstractHibernateManager {
	
	private static MesaDao instancia = null;
	
	public static MesaDao getInstancia() {
		if(instancia == null) {
			instancia = new MesaDao();
		}
		return instancia;
	}
	public void save (MesaEntity mesa){
		Session s = null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.persist(mesa);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[mesa SAVED ON TABLE mesas]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
	}
	
	public List<MesaEntity> obtenerMesas() {
		@SuppressWarnings("unchecked")
		List<MesaEntity> mesas = (List<MesaEntity>) findAll("MesaEntity");
		return mesas;
	}
	@SuppressWarnings("unchecked")
	public MesaEntity obtenerMesa(Integer idMesa) {
		Session s = null;
		MesaEntity mesa = new MesaEntity();
		
		try {
			s = getNewSession();
			mesa = (MesaEntity) s.createQuery("FROM MesaEntity m " +
									  "WHERE m.id = :idMesa")
							  .setInteger("idMesa", idMesa)
							  .uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return mesa;	
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<MesaEntity> obtenerMesasLibres() {
		Session s = null;
		ArrayList<MesaEntity> mesasLibres = new ArrayList<MesaEntity>();
		try {
			s = getNewSession();
			@SuppressWarnings({ "rawtypes" })
			List lista = s.createQuery("FROM MesaEntity m " +
								  "WHERE m.estado = :estado")
							  .setString("estado", "libre")
							  .list();
			mesasLibres = (ArrayList<MesaEntity>) lista;
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return mesasLibres;	
	}
	
	public void modificarMesa(MesaEntity mesa) {
		Session s = null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.merge(mesa);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[mesa UPDATED ON TABLE mesas]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
	}
}
